<?php
/**
 * Created by IntelliJ IDEA.
 * User: ahwwl
 * Date: 18-8-9
 * Time: 下午6:06
 */

namespace app\controller;


use app\common\weixin;
use app\model\CompanyList;
use app\model\OrderList;
use app\model\UserCardList;
use app\model\WalletLog;
use think\Db;
use think\Request;

/**
 * @property UserCardList UserCardList
 * @property OrderList OrderList
 * @property CompanyList CompanyList
 * @property WalletLog WalletLog
 */
class Companyservice extends CommonController
{
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->UserCardList = new UserCardList();
        $this->OrderList = new OrderList();
        $this->CompanyList = new CompanyList();
        $this->WalletLog = new WalletLog();
    }
    function index()
    {
        $info = $this->CompanyList->where(["id"=>$this->company_id])->find();
        $this->assign("info",$info);
        $this->assign("page_title", "上游信息");
        return $this->fetch();
    }
    function card_list()
    {

        $this->assign("page_title","代理卡列表");
        return $this->fetch();
    }
    function ajax_card_list()
    {
        try
        {
            if($this->company_id<1)
            {
                exception("非客户");
            }
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $mobile = input("mobile","","trim");
            $real_name = input("real_name","","trim");
            $card_no = input("card_no","","trim");

            $where = [];
            if(!empty($mobile))
                $where["b.mobile"] = $mobile;
            if(!empty($real_name))
                $where["b.real_name"] = ["like",$real_name."%"];
            if(!empty($card_no))
                $where["a.card_no"] = ["like","%".$card_no."%"];
            $where["a.company_id"] = $this->company_id;
            $count = $this->UserCardList->alias("a")
                ->join("f_user_list b","a.user_id=b.id","left")
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->UserCardList->alias("a")
                ->join("f_user_list b","a.user_id=b.id","left")
                ->join("f_company_list cl" ,"cl.id=a.company_id","left")
                ->join("f_apply_list al","al.company_id=a.company_id and  al.card_no=a.card_no and al.status=2","left")
                ->field("a.*,b.real_name,b.mobile,cl.name as company_name,al.plate_number")
                ->where($where)
                ->order("a.id desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();
            $user_card_idle_list = $this->UserCardList->where(["user_id"=>0,"card_type"=>["GT",0]])->select();
            $this->resultdata["user_card_idle_list"] = $user_card_idle_list;
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }

    function order_list()
    {
        $this->assign("page_title","代理卡列表");
        return $this->fetch();
    }
    function ajax_order_list()
    {
        try
        {
            if($this->company_id<1)
            {
                exception("非客户");
            }
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $order_no = input("order_no","","trim");
            $third_no = input("third_no","","trim");
            $card_no = input("card_no","","trim");
            $user_mobile = input("user_mobile","","trim");
            $mobile = input("mobile","","trim");
            $pay_type = input("pay_type",0,"intval");
            $pay_status = input("pay_status",0,"intval");
            $delivery_status = input("delivery_status",0,"intval");
            $status = input("status",0,"intval");
            $date_1 = input("date_1",get_date_time("Y-m-d"),"trim");
            $date_2 = input("date_2",get_date_time("Y-m-d"),"trim");
            if($date_1 > $date_2)
                $this->E("选择日期出错");

            $date_1 = strtotime($date_1);

            if(empty($date_1))
                $date_1 = strtotime("today");
            $date_2 = strtotime($date_2);
            if(empty($date_2))
                $date_2 = strtotime("today");
            $where = [];
            if(!empty($order_no))
                $where["ol.order_no"] = $order_no;
            if(!empty($third_no))
                $where["ol.third_no"] = $third_no;
            if(!empty($card_no))
                $where["ol.card_no"] = $card_no;
            if(!empty($user_mobile))
                $where["ul.mobile"] = $user_mobile;
            if(!empty($mobile))
                $where["ol.mobile"] = $mobile;
            if(in_array($pay_type,[0,1,2]))
                $where["ol.pay_type"] = $pay_type;
            if(in_array($pay_status,[0,1,2,3]))
                $where["ol.pay_status"] = $pay_status;
            if(in_array($delivery_status,[0,1,2,3]))
                $where["ol.delivery_status"] = $delivery_status;
            if(in_array($status,[0,1,2,3]))
                $where["ol.status"] = $status;
            $where["ol.ctime"] = ["between",[$date_1,$date_2+86400-1]];
            $where["ol.is_delete"] = 0;
            $where["ol.company_id"] = $this->company_id;
            $count = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->join("f_company_list cpl","cpl.id=ol.company_id","left")
                ->where($where)
                ->field("ol.*,ul.mobile as user_mobile,cpl.name as company_name")
                ->order("ol.ctime desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();

            $money_list = $this->OrderList->alias("ol")
                ->join("f_user_list ul","ul.id=ol.user_id","left")
                ->join("f_card_package_list cpl","cpl.id=ol.product_id","left")
                ->join("f_agent_list al","al.id=ol.agent_id","left")
                ->where($where)
                ->field(['sum(ol.total_money) as count_total_money',
                    'sum(if(ol.status=2,ol.cost,0)) as count_cost',
                    'sum(if(ol.status=2,ol.card_fee,0)) as count_card_fee',
                    'sum(if(ol.status=2,ol.total_money-ol.card_fee-ol.cost,0)) as count_profit',
                    'sum(if(ol.pay_type=3,ol.supply_cost,0)) as count_pay_supply_cost',
                    'sum(ol.supply_cost) as count_supply_cost'
                ])
                ->find();
            $this->resultdata["money_list"] = $money_list;
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_add_order()
    {
        try {

            if($this->company_id<1)
            {
                exception("非客户");
            }
            $row_list = input("row_list/a", []);
            $amount = input("amount",0,"intval");
            $is_pay = input("is_pay",0,"intval");

            if (empty($row_list) ||empty($amount)) {
                $this->E("参数不正确");
            }
            $amount = $amount*10000;
            $list = make_array($row_list,"card_no");
            if (empty($list) ) {
                $this->E("参数不正确");
            }


            $CardListInfo = $this->UserCardList->where(['card_no' => ["in",$list],"company_id" =>$this->company_id,"card_type"=>2,"status"=>1])->select();
            $card_lists = make_array($CardListInfo,"card_no");
            if(count($list) != count($card_lists))
            {
                $this->E("不存在卡号：".json_encode(array_diff($card_lists,$list)));
            }
            $company_list = $this->CompanyList->where(['id' => $this->company_id,"status"=>0])->select();
            $company_list = make_array_key($company_list,"id",true);
            $order_info_list = [];
            $wallet_info_list = [];
            $total_money_list = [];
            foreach ($CardListInfo as $card_info)
            {
                $card_no = $card_info["card_no"];
                $card_type = $card_info["card_type"];
                $company_id = $card_info["company_id"];
                if(empty($company_list[$company_id]))
                    \exception("企业不存在");
                $company_info = $company_list[$company_id];
                $agent_id = $company_info["agent_id"];
                $discount= $company_info["discount"];
                $balance = $company_info["balance"];
                $credit = $company_info["credit"];
                $basic_price = $amount;
                $cost = $basic_price*COST_DISCOUNT;
                $money = $basic_price*$discount/10000;
                $ip = $this->request->ip();
                $order_info = $this->OrderList->addCompanyCardOrder($agent_id,$company_id,$card_no,$card_type,$basic_price,$cost,$money,0,$money,$ip);
                $order_no = $order_info["order_no"];
                if($is_pay == 1)
                {
                    if(($balance+$credit)<$money)
                        \exception("企业预存款不足:".$company_id);
                    $company_list[$company_id]["balance"] -= $money;
                    $order_info["pay_status"] = 1;
                    $wallet_info = [
                        "company_id" =>$company_id,
                        "type" =>4,
                        "order_no" =>$order_no,
                        "money" =>-$money,
                        "info"=>"卡充值",
                        "ctime"=>NOW_TIME,
                    ];
                    $wallet_info_list[] = $wallet_info;
                }
                $order_info_list[] = $order_info;
                if(empty($total_money_list[$company_id]))
                    $total_money_list[$company_id] = 0;
                $total_money_list[$company_id] +=$money;
            }

            Db::startTrans();
            try{
                if($is_pay == 1)
                {
                    foreach ($total_money_list as $key=>$value)
                    {
                        $query = $this->CompanyList->where(["id"=>$key])
                            ->where("(balance+credit)>=".$value)->setDec("balance", $value);
                        if(!$query)
                            \exception("企业余额不足");
                    }
                }
                $query = $this->OrderList->insertAll($order_info_list);
                if(empty($query))
                {
                    exception("提交订单添加失败");
                }
                if($wallet_info_list)
                {
                    $query = $this->WalletLog->insertAll($wallet_info_list);
                    if(empty($query))
                    {
                        exception("订单消费记录添加失败");
                    }
                }


                Db::commit();
            }catch (\Exception $e)
            {
                Db::rollback();
                \exception($e->getMessage());
            }
            $this->resultdata["error"] = 0;
        } catch (\Exception $e) {
            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_add_weixin_pay()
    {
        try
        {
            $order_no = input("order_no","","trim");
            if(empty($order_no))
            {
                exception("参数不能为空");
            }


            $order_info = $this->OrderList->alias("ol")
                ->where(["ol.order_no" => $order_no])
                ->find();
            if(empty($order_info))
            {
                exception("订单信息不存在");
            }
//            if(empty($order_info["goods_id"]))
//            {
//                exception("套餐不存在");
//            }
            $order_no = $order_info["order_no"];
            $pay_order_no = $order_info["pay_order_no"];
            $token_type = $order_info["token_type"];
            $card_no = $order_info["card_no"];
            if(empty($card_no))
            {
                exception("卡号不能为空");
            }
            $weixin = new weixin();
            $notify_url = FUELURL."/order/weixinNotify";
            $jsApiParameters = "";
            if($pay_order_no)
            {
                $is_Close = $weixin->CloseOrder($pay_order_no,$token_type);
                if(!$is_Close)
                    exception("支付异常");
            }

            $pay_order_no = get_order_no("P",$order_no);
            $query = $this->OrderList->where(["order_no"=>$order_no])->update(["pay_order_no"=>$pay_order_no]);
            if(!$query)
                exception("提交失败");
            $money = ceil($order_info["total_money"]/100);
            $money += ceil($money*0.006);
            $jsApiParameters = $weixin->GetWeiXinNATIVEUnifiedOrder($pay_order_no,$money,"充值:".$card_no,$notify_url);

            $this->resultdata["data"]["jsApiParameters"] = $jsApiParameters;
            $this->resultdata["data"]["order_no"] = $order_no;
            $this->resultdata["error"] = 0;

        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }
        return $this->ajaxResult();
    }
    function company_list()
    {
        return $this->fetch();
    }
    function ajax_company_list()
    {
        try
        {
            if($this->company_id<1)
            {
                exception("非客户");
            }
            $page = input("page",1,"intval");
            $rows = input("rows",30,"intval");
            $name = input("name","","trim");

            $where = [];

            if(!empty($name))
                $where["b.name"] = ["like",$name."%"];
            $where["pid"] = $this->company_id;
            $count = $this->CompanyList
                ->where($where)
                ->count();
            $page_total = ceil($count/$rows);
            $page = $page>$page_total?$page_total:$page;
            $page = $page < 1? 1:$page;
            $order_log = $this->CompanyList
                ->where($where)
                ->order("id desc")
                ->limit(($page-1)*$rows,$rows)
                ->select();
            $this->resultdata["data"] = $order_log;
            $this->resultdata["error"] = 0;
            $this->resultdata["total"] = $count;
            $this->resultdata["page"] = $page;
            $this->resultdata["rows"] = $rows;
        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
    function ajax_company_allot_balance()
    {
        try
        {
            if($this->company_id<1)
            {
                exception("非客户");
            }
            $id = input("id",0,"intval");
            $balance = input("balance",0,"intval");

            if (empty($id) ||empty($balance)) {
                exception("参数不正确");
            }
            $balance = $balance*10000;

            $where = [];
            $where["pid"] = $this->company_id;
            $where["id"] = $id;
            $info  = $this->CompanyList
                ->where($where)
                ->find();
            if(empty($info))
                exception("子账户信息错误");
            if($info["status"] == 1)
                exception("子账户禁用");
            Db::startTrans();
            try
            {
                if($balance>0)
                {
                    $query = $this->CompanyList->where(["id"=>$id])->setInc("balance",$balance);
                }else{
                    $query = $this->CompanyList->where(["id"=>$id,"balance"=>["EGT",-$balance]])->setDec("balance",-$balance);
                }
                if(empty($query))
                {
                    $this->E("子账户分配资金失败");
                }
                if($balance>0)
                {
                    $query = $this->CompanyList->where(["id"=>$this->company_id,"balance"=>["EGT",$balance]])->setDec("balance",$balance);
                }else{
                    $query = $this->CompanyList->where(["id"=>$this->company_id])->setInc("balance",-$balance);
                }

                if(empty($query))
                {
                    $this->E("分配资金失败");
                }
                $wallet_info = [
                    "company_id"=>$id,
                    "type"=>5,
                    "money"=>$balance,
                    "info"=>"分配资金：".($balance/10000),
                    "ctime"=>NOW_TIME

                ];
                $query = $this->WalletLog->insert($wallet_info);
                if(empty($query))
                {

                    $this->E("流水添加失败");
                }
                $wallet_info = [
                    "company_id"=>$this->company_id,
                    "type"=>5,
                    "money"=>-$balance,
                    "info"=>"分配资金支出：".($balance/10000),
                    "ctime"=>NOW_TIME

                ];
                $query = $this->WalletLog->insert($wallet_info);
                if(empty($query))
                {

                    $this->E("流水添加失败");
                }
                Db::commit();
            }catch (\Exception $e)
            {
                Db::rollback();
                exception($e->getMessage());
            }

            $this->resultdata["error"] = 0;

        }catch (\Exception $e)
        {

            $this->resultdata["msg"] = $e->getMessage();
        }

        echo json_encode($this->resultdata);
    }
}